﻿using Common.Helper;
using Common.Model;
using Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Script.Serialization;
using System.Xml;
using WxPayAPI;
using System.Web.Configuration;
namespace Common.Wx
{
    public class WxHelper
    {

        public static string APPID = WebConfigurationManager.AppSettings["APPID"];
        public static string APPSECRET = WebConfigurationManager.AppSettings["APPSECRET"];
        public static string filePath = WxPayConfig.FILEPATH;
        /// <summary>
        /// 获取微信用户的Token(只是提到，扫一扫项目不需要)
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public Access_Token GetToken(string code)
        {

            string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", APPID, APPSECRET, code);
            string json = HttpHelper.GetHtml(url);
            return JsonHelper.DeserializeObject<Access_Token>(json);
        }
        /// <summary>
        /// 签名算法 对string1进行sha1签名，得到signature
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static Wechat_Sdk GetSdk(string url)
        {
            string noncestr = GuidHelper.GuidTo16String();
            string timestamp = DateTime.Now.Ticks.ToString().Substring(0,10);
            Wechat_Ticket Wechat_Ticket = GetTicket();
            string string1 = "jsapi_ticket=" + Wechat_Ticket.ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url + "";
            string signature = MD5Helper.SHA1(string1);
            Wechat_Sdk sdk = new Wechat_Sdk();
            sdk.noncestr = noncestr;
            sdk.timestamp = timestamp;
            sdk.signature = signature;
            return sdk;
        }


        /// <summary>
        /// 获取微信用户的Token   
        /// 基础支持的token 和 上面方法（网页授权）的token不一样
        /// 网页授权的token是用户的token，每人一个不一样的， 基础支持的token是公众号的需要调取某些接口使用的token
        /// 网页授权没有次数限制  基础支持的token 有次数限制（2000次）
        /// 具体查看链接：http://blog.csdn.net/dreamparks/article/details/51745413
        /// </summary>
        /// <returns></returns>
        //private static string GetBasics_Token()
        //{
        //    备注：基础支持的Token，应该存起来使用，因为每天只能调用2000次，很快就会过期，所以劲量使用几分钟一刷新Token
        //    string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", AppId, AppSecret);
        //    string json = HttpHelper.GetHtml(url);
        //    Access_Token token = JsonHelper.DeserializeObject<Access_Token>(json);
        //    string baseics_Token = token.access_token;
        //    return baseics_Token;
        //}

        /// <summary>
        /// 获取微信 Ticket
        /// </summary>
        /// <returns></returns>
        private static Wechat_Ticket GetTicket()
        {
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", IsExistAccess_Token());
            string json = HttpHelper.GetHtml(url);
            return JsonHelper.DeserializeObject<Wechat_Ticket>(json);
        }

        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <param name="AppID"></param>
        /// <param name="AppSecret"></param>
        /// <returns></returns>
        public static Access_Token GetAccessToken()
        {
            JavaScriptSerializer Jss = new JavaScriptSerializer();
            string respText = CommonMethod.WebRequestPostOrGet(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", APPID, APPSECRET), "");
            Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText);
            Access_Token mode = new Access_Token();
            mode.access_token = respDic["access_token"].ToString();
            mode.expires_in = respDic["expires_in"].ToString();
            return mode;
        }


        /// <summary>
        /// 获取Access_token值
        /// </summary>
        /// <returns></returns>
        public static string IsExistAccess_Token()
        {
            string Token = string.Empty;
            DateTime YouXRQ;
            DateTime _youxrq = DateTime.Now;
            using (Entities db = new Entities())
            {

                var myaccess = db.wxAccess.FirstOrDefault();
                if (myaccess == null)
                {
                    wxAccess newWxAccess = new wxAccess();
                    Access_Token mode = GetAccessToken();
                    newWxAccess.Access_Token = mode.access_token;
                    newWxAccess.Access_YouXRQ = _youxrq.AddSeconds(60);
                    db.wxAccess.Add(newWxAccess);
                    db.SaveChanges();
                    Token= mode.access_token;
                }
                else
                {
                    Token = myaccess.Access_Token;
                    YouXRQ = Convert.ToDateTime(myaccess.Access_YouXRQ);
                    if (DateTime.Now > YouXRQ)
                    {
                        Access_Token mode = GetAccessToken();
                        myaccess.Access_Token = mode.access_token;
                        myaccess.Access_YouXRQ = _youxrq.AddSeconds(60);
                        db.SaveChanges();
                        Token = myaccess.Access_Token;
                    }

                }

            }
            return Token;

        }

    }
}
